import tokenMgr from "../cookieMgr/tokenMgr";

let sending = [];
// fetch.js
const request = async (url, options = {}) => {
  try {
    const path = url.split("?")[0].toLowerCase();
    if (sending.findIndex((d) => d.path === path) != -1) {
      sending.find((d) => d.path === path).controller.abort();
      sending = sending.filter((d) => d.path != path);
    }
    //  创建 AbortController 实例
    const controller = new AbortController();
    const signal = controller.signal;
    options.signal = signal;
    sending.push({ path, controller });
    const response = await fetch(url, options);
    sending = sending.filter((d) => d.path != path);
    // 如果响应状态码不在200-299范围内，视为错误
    if (!response.ok) {
      if (response.status === 401) {
        location.href = "/login";
      }
      const error = new Error("请求失败");
      error.code = response.status;
      error.info = await response.json(); // 假设后端返回JSON格式的错误信息
      throw error;
    }

    return await response.json(); // 成功时返回解析后的数据
  } catch (error) {
    // 统一处理网络错误或业务错误
    console.error("请求异常:", error);
    return error;
    // throw new Error(error.message || "网络请求失败"); // 抛出错误供调用方处理
  }
};

const instance = {
  get: (url, params = {}, options = {}) => {
    // 从本地存储获取token，根据实际情况修改获取方式
    const token = tokenMgr.getToken();

    // 合并请求头，自动携带token
    const headers = {
      "Content-Type": "application/json",
      ...options.headers,
      Authorization: `Bearer ${token}`,
    };
    return request(
      import.meta.env.VITE_APP_API_URL +
        (url.startsWith("/") ? url : "/" + url) +
        "?" +
        new URLSearchParams(params),
      {
        ...{ headers, ...options },
        method: "get",
      }
    );
  },
  post: (url, data = {}, options = {}) => {
    // 从本地存储获取token，根据实际情况修改获取方式
    const token = tokenMgr.getToken();

    // 合并请求头，自动携带token
    const headers = {
      "Content-Type": "application/json",
      ...options.headers,
      Authorization: `Bearer ${token}`,
    };
    return request(
      import.meta.env.VITE_APP_API_URL +
        (url.startsWith("/") ? url : "/" + url),
      { body: JSON.stringify(data), ...{ headers, ...options }, method: "post" }
    );
  },
  upload: (url, formData = new FormData(), options = {}) => {
    // 从本地存储获取token，根据实际情况修改获取方式
    const token = tokenMgr.getToken();
    // 携带token
    const headers = {
      ...options.headers,
      Authorization: `Bearer ${token}`,
    };

    return request(
      import.meta.env.VITE_APP_API_URL +
        (url.startsWith("/") ? url : "/" + url),
      {
        body: formData,
        ...{ headers, ...options },
        method: "post",
      }
    );
  },
};

export { request, instance };
